import React, { useState, useEffect } from 'react'
import { NavBar, Input, TextArea, Toast, Button } from 'antd-mobile'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { editBlog, getBlog } from '../../api'
import './index.css'


export default function Publish() {
  const [context, setContext] = useState('')
	const [title, setTitle] = useState('')
	const [src, setSrc] = useState('')
	const navigate = useNavigate()
	const [search] = useSearchParams()
	const id = search.get('id')

	useEffect(()=>{
		if(id){
			async function blogData() {
				const blog = await getBlog({id})
				setTitle(blog[0].title)
				setContext(blog[0].context)
				setSrc(blog[0].src)
			}
			blogData()
		}
	},[id])

	function cancel(){
		navigate(-1)
	}

	async function save(){
		if(!context.trim()||!title.trim()||!src.trim()) return Toast.show({ icon: 'fail', content: "不能为空", maskClickable:false })
		try {
			await editBlog({id,context,title,src})
			navigate(-1)
		} catch (error) {
			console.log(error);
			if (error.code===451) {
				setTimeout(() => {
          navigate('/login')
        }, 2000);
			}
			Toast.show({ icon: 'fail', content: error.message, maskClickable:false })
		}
    
	}

  return (	
    <div id='publish'>
			<NavBar className='navbar' onBack={cancel} right={<Button onClick={save} color='primary' size='small' fill='solid'>发表</Button>}>写博客</NavBar>
			<div className='edit-input'>
				<Input placeholder='请输入标题'
					clearable 
					maxLength={30}
					value={title}
					onChange={val => {
						setTitle(val)
					}}/>
				<Input placeholder='请输入网址'
					clearable
					value={src}
					onChange={val => {
						setSrc(val)
					}}/>
				<TextArea
					placeholder='请输入内容'
					value={context}
					onChange={val => {
						setContext(val)
					}}
					showCount
					autoSize={{ minRows: 10 }}
					maxLength={9999}
				/>
			</div>
			
			
			
    </div>
  )
}
